package action.album;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import service.AlbumService;
import service.PhotoService;
import bean.Photo;

import com.opensymphony.xwork2.ActionSupport;

public class SavePhotoAction extends ActionSupport {
	private File file;
	private String fileFileName;
	private String fileContentType;
	private Photo photo;
	private PhotoService photoService;
	private AlbumService albumService;
	
	@Override
	public String execute() throws Exception {
		String filename;
		if(file==null){
			return SUCCESS;
		}else{
			
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			int d=(int)Math.random()*100;
			filename=df.format(new Date()).toString()+d+fileFileName.substring(fileFileName.lastIndexOf('.'));
			photo.setImage("photo/"+filename);
			photo.setAlbum(albumService.getAlbumById(photo.getAlbum().getId()));
			photoService.addPhoto(photo);
			byte[] buffer=new byte[1024];
			InputStream in=new FileInputStream(file);
			OutputStream out=new FileOutputStream(new File(ServletActionContext.getServletContext().getRealPath("/photo")+"/"+filename));
			int length=in.read(buffer);
			while(length>0){
				out.write(buffer);
				length=in.read(buffer);
			}
			in.close();
			out.flush();
			out.close();
			return SUCCESS;
		}
	}

	public Photo getPhoto() {
		return photo;
	}

	public void setPhoto(Photo photo) {
		this.photo = photo;
	}

	public PhotoService getPhotoService() {
		return photoService;
	}

	public void setPhotoService(PhotoService photoService) {
		this.photoService = photoService;
	}

	public AlbumService getAlbumService() {
		return albumService;
	}

	public void setAlbumService(AlbumService albumService) {
		this.albumService = albumService;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
}
